package com.ca.ridersclubapplication.view.input;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ea.ui.core.basic.EATextField;

import java.util.ArrayList;
import java.util.List;

public class PaperEditInput extends ConstraintLayout {

    private String label;
    private String hint;

    public TextView labelView;
    public EATextField inputView;
    public TableLayout imageTL;
    public ConstraintLayout addImageButton;

    //  存放ImageView的TableRow列表
    private final List<TableRow> rowList = new ArrayList<>();
    private int currentLine = -1;

    //  存放图片路径
    private final List<String> pathList = new ArrayList<>();

    //  存放ImageView
    private final List<List<PaperEditImage>> editList = new ArrayList<>();

    public PaperEditInput(@NonNull Context context) {
        super(context);
        initView(context, null);
    }

    public PaperEditInput(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public PaperEditInput(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        View view = LayoutInflater.from(context).inflate(R.layout.paper_edit_item_layout, this);
        imageTL = view.findViewById(R.id.tl_image);
        labelView = view.findViewById(R.id.tv_label);
        inputView = view.findViewById(R.id.input_content);
        addImageButton = view.findViewById(R.id.cl_addImage);

        inputView.setBackgroundColor(getResources().getColor(R.color.base_background));

        if (attrs != null) {
            TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PaperEditInput, 0, 0);

            label = array.getString(R.styleable.PaperEditInput_pei_label);
            hint = array.getString(R.styleable.PaperEditInput_pei_hint);

            array.recycle();
        }

        addImageButton.setOnClickListener(v -> {});

        setLabel(label);
        setHint(hint);
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label == null ? "" : label;
        labelView.setText(this.label);
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint == null ? "" : hint;
        inputView.setHint(this.hint);
    }


    /**
     * 初始化行
     */
    private void initRow(TableRow row) {
        //  设置布局参数
        TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(rowParams);
    }

    /**
     * 初始化图片视图
     */
    private void initEdit(PaperEditImage edit, int i, int j) {

        //  设置布局参数
        initEitLayoutParams(edit);

        //  设置图片视图中的删除按钮点击事件
        edit.deleteButton.setOnClickListener(v -> {
            deleteImage(i, j);
        });
    }

    private void initEitLayoutParams(PaperEditImage edit) {
        //  保持图片不变形
        edit.iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //  设置图片比重、外边距
        TableRow.LayoutParams params = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1);
        params.setMargins(8, 8, 8, 8);
        edit.setLayoutParams(params);
        //  设置高度和宽度一致
        edit.post(() -> {
            ViewGroup.LayoutParams elp = edit.getLayoutParams();
            elp.height = edit.getWidth();
            edit.setLayoutParams(elp);
        });
    }

    /**
     * 添加图片
     */
    public void addImage(String path) {

        //  判断是否需要添加新的一行
        if (pathList.size() % 3 == 0) {
            //  创建新的一行
            TableRow row = new TableRow(getContext());
            editList.add(new ArrayList<>());
            //  初始化该行
            initRow(row);
            //  在布局中添加该行
            imageTL.addView(row);
            //  在列表中添加改行
            rowList.add(row);

            //  添加一行时，填充三个空白占位
            for (int i = 0; i < 3; i++) {
                PaperEditImage emptyEdit = new PaperEditImage(getContext());
                initEitLayoutParams(emptyEdit);
                emptyEdit.deleteButton.setVisibility(GONE);
                row.addView(emptyEdit);
            }
        }

        //  因为上面在创建一个新行时，总会添加三个占位视图，因此在添加图片前删除下一个位置即可
        //  计算下一个位置的下标
        int nextIndex = pathList.size() % 3;
        TableRow row = rowList.get(pathList.size() / 3);
        row.removeViewAt(nextIndex);

        //  创建新的一个图片视图
        PaperEditImage edit = new PaperEditImage(getContext());
        //  显示图片
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        edit.iv.setImageBitmap(bitmap);
        //  计算该视图在二维数组中的行列坐标
        int i = pathList.size() / 3;
        int j = pathList.size() % 3;
        //  设置该图片视图布局参数
        initEdit(edit, i, j);
        //  在布局中添加该视图
        row.addView(edit, nextIndex);
        editList.get(pathList.size() / 3).add(edit);

        //  添加图片地址
        pathList.add(path);
    }


    /**
     * 删除图片
     */
    public void deleteImage(int i, int j) {

        if (pathList.size() == 0) {
            Log.e("PaperEditInput", "deleteImage(" + i + ", " + j + ") 失败：当前没有元素");
            return;
        }

        //  计算初始下标（pathList）
        int index = i * 3 + j;
        if (index >= pathList.size()) {
            Log.e("PaperEditInput",
                    "deleteImage(" + i + ", " + j + ") 失败：下标越界，pathList.size() = " + pathList.size());
            return;
        }

        //  获取当前最大行数
        int line = pathList.size() / 3 + pathList.size() % 3 == 0 ? 0 : 1;

        int row = i;
        int col = j;
        int nextIndex = row * 3 + col + 1;
        int nextRow = nextIndex / 3;
        int nextCol = nextIndex % 3;

        do  {

            if (nextIndex >= pathList.size()) {
                break;
            }

            //  获取当前视图
            PaperEditImage edit = editList.get(row).get(col);
            //  获取下一个视图
            PaperEditImage nextEdit = editList.get(nextRow).get(nextCol);

            //  将下一个视图的图片覆盖到当前视图
            edit.iv.setImageDrawable(nextEdit.iv.getDrawable());

            //  将当前坐标移动到下一个坐标
            row = nextRow;
            col = nextCol;

            //  计算下一个坐标
            nextIndex = row * 3 + col + 1;
            nextRow = nextIndex / 3;
            nextCol = nextIndex % 3;

        } while (nextIndex < pathList.size());

        //  布局中将该视图设为不可见（row, col）
        PaperEditImage edit = editList.get(row).get(col);
        edit.iv.setImageBitmap(null);
        edit.deleteButton.setEnabled(false);
        edit.deleteButton.setVisibility(GONE);
        //  二维数组中移除该元素
        editList.get(row).remove(col);

        //  移除pathList对应数据
        pathList.remove(index);

        //  判断是否存在空的TableRow
        int newLine = pathList.size() / 3 + (pathList.size() % 3 == 0 ? 0 : 1);
        while (rowList.size() > newLine) {
            //  移除rowList中的空行，并获取该行
            int removeIndex = rowList.size() - 1;
            TableRow r = rowList.remove(removeIndex);
            //  移除视图中的空行
            imageTL.removeView(r);
        }
        while (editList.size() > newLine) {
            //  移除editList中的空行
            editList.remove(editList.size() - 1);
        }
    }

    public List<String> getPathList() {
        return pathList;
    }
}
